package jonet

import (
	"fmt"
	"gitee.com/jolib/jokode"
	"github.com/pkg/errors"
	"net"
	"strconv"
	"strings"
	"time"
)

func ParseAddr(addr string) (host string, port int, err error) {
	idx := strings.LastIndexByte(addr, ':')
	portStr := "0"

	if idx > 0 {
		host = addr[:idx]
		portStr = addr[idx+1:]
	} else {
		host = addr
	}

	if port, err = strconv.Atoi(portStr); err != nil {
		return "", -1, errors.Wrapf(err, "try convert port info '%s' to number fail", portStr)
	} else {
		return host, port, nil
	}
}

func GetLocalIpByRemoteTcp(remoteHost string, remotePort uint64, timeOut time.Duration) (net.IP, error) {
	var connObj net.Conn

	defer func() {
		if connObj != nil {
			if err := connObj.Close(); err != nil {
				jokode.Errorf("try close tcp connection fail, error info: %v", err)
			}
			connObj = nil
		}
	}()

	if conn, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", remoteHost, remotePort), timeOut); err != nil {
		return nil, errors.Wrapf(err, "try connect remote addr '%s:%d' fail", remoteHost, remotePort)
	} else {
		localAddrStr := conn.LocalAddr().String()
		if localAddr, err2 := net.ResolveTCPAddr("tcp", localAddrStr); err2 != nil {
			return nil, errors.Wrapf(err2, "try parse local addr '%s' fail", localAddrStr)
		} else {
			return localAddr.IP, nil
		}
	}
}
